package com.ljh.onlinetest.controller.student;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ljh.onlinetest.base.BaseApiController;
import com.ljh.onlinetest.base.RestResponse;
import com.ljh.onlinetest.domain.*;
import com.ljh.onlinetest.domain.enums.ExamPaperAnswerStatusEnum;
import com.ljh.onlinetest.domain.enums.ExamPaperTypeEnum;
import com.ljh.onlinetest.event.CalculateExamPaperAnswerCompleteEvent;
import com.ljh.onlinetest.event.UserEvent;
import com.ljh.onlinetest.service.ExamPaperAnswerService;
import com.ljh.onlinetest.service.ExamPaperService;
import com.ljh.onlinetest.service.SubjectService;
import com.ljh.onlinetest.utils.DateTimeUtil;
import com.ljh.onlinetest.utils.ExamUtil;
import com.ljh.onlinetest.utils.PageInfoHelper;
import com.ljh.onlinetest.viewmodel.admin.paper.PaperEditRequestVM;
import com.ljh.onlinetest.viewmodel.student.exam.ExamPaperReadVM;
import com.ljh.onlinetest.viewmodel.student.exam.ExamPaperSubmitVM;
import com.ljh.onlinetest.viewmodel.student.exampaper.ExamPaperAnswerPageResponseVM;
import com.ljh.onlinetest.viewmodel.student.exampaper.ExamPaperAnswerPageVM;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;

/**
 * @author ljh
 * @ClassName ExamPaperAnswerController.java
 * @createTime 2022年03月09日
 */
@RestController("StudentExamPaperAnswerController")
@RequestMapping("/api/student/exampaper/answer")
public class ExamPaperAnswerController extends BaseApiController {

    private final ExamPaperAnswerService examPaperAnswerService;
    private final ExamPaperService examPaperService;
    private final SubjectService subjectService;
    private final ApplicationEventPublisher eventPublisher;

    @Autowired
    public ExamPaperAnswerController(ExamPaperAnswerService examPaperAnswerService, ExamPaperService examPaperService, SubjectService subjectService, ApplicationEventPublisher eventPublisher) {
        this.examPaperAnswerService = examPaperAnswerService;
        this.examPaperService = examPaperService;
        this.subjectService = subjectService;
        this.eventPublisher = eventPublisher;
    }

    @PostMapping("/answerSubmit")
    public RestResponse answerSubmit(@RequestBody @Valid ExamPaperSubmitVM examPaperSubmitVM){
        User user = getCurrentUser();
        ExamPaperAnswerInfo examPaperAnswerInfo = examPaperAnswerService.calculateExamPaperAnswer(examPaperSubmitVM,user);
        if (null == examPaperAnswerInfo){
            return RestResponse.fail(2,"试卷不能重复做");
        }
        ExamPaperAnswer examPaperAnswer = examPaperAnswerInfo.getExamPaperAnswer();
        Integer userScore = examPaperAnswer.getUserScore();
        String scoreVm = ExamUtil.scoreToVM(userScore);
        UserEventLog userEventLog = new UserEventLog(user.getId(), user.getUserName(), user.getRealName(), new Date());
        String content = user.getUserName() + "提交试卷：" + examPaperAnswerInfo.getExamPaper().getName()
                + "得分：" + scoreVm
                + "耗时：" + ExamUtil.secondToVM(examPaperAnswer.getDoTime());
        userEventLog.setContent(content);
        eventPublisher.publishEvent(new CalculateExamPaperAnswerCompleteEvent(examPaperAnswerInfo));
        eventPublisher.publishEvent(new UserEvent(userEventLog));
        return RestResponse.ok(scoreVm);
    }


    @PostMapping("/read/{id}")
    public RestResponse<ExamPaperReadVM> read(@PathVariable Integer id){
        //根据试卷id获取试卷答案
        ExamPaperAnswer examPaperAnswer = examPaperAnswerService.selectById(id);
        ExamPaperReadVM examPaperReadVM = new ExamPaperReadVM();
        //获取试卷信息model
        PaperEditRequestVM paper = examPaperService.examPaperToVM(examPaperAnswer.getExamPaperId());
        //获取答案信息model
        ExamPaperSubmitVM answer = examPaperAnswerService.examPaperAnswerToVM(examPaperAnswer.getId());
        examPaperReadVM.setPaper(paper);
        examPaperReadVM.setAnswer(answer);
        return RestResponse.ok(examPaperReadVM);
    }

    /**
     * 考试记录分页
     * @param model
     * @return
     */
    @PostMapping("/pageList")
    public RestResponse<PageInfo<ExamPaperAnswerPageResponseVM>> pageList(@RequestBody @Valid ExamPaperAnswerPageVM model){
        model.setCreateUser(getCurrentUser().getId());
        PageInfo<ExamPaperAnswer> pageInfo = examPaperAnswerService.studentPage(model);
        PageInfo<ExamPaperAnswerPageResponseVM> vmPageInfo = PageInfoHelper.copyMap(pageInfo, e -> {
            ExamPaperAnswerPageResponseVM answerPageResponseVM = modelMapper.map(e, ExamPaperAnswerPageResponseVM.class);
            Subject subject = subjectService.selectById(answerPageResponseVM.getSubjectId());
            answerPageResponseVM.setDoTime(ExamUtil.secondToVM(e.getDoTime()));
            answerPageResponseVM.setSystemScore(ExamUtil.scoreToVM(e.getSystemScore()));
            answerPageResponseVM.setUserScore(ExamUtil.scoreToVM(e.getUserScore()));
            answerPageResponseVM.setPaperScore(ExamUtil.scoreToVM(e.getPaperScore()));
            answerPageResponseVM.setSubjectName(subject.getName());
            answerPageResponseVM.setCreateTime(DateTimeUtil.dateFormat(e.getCreateTime()));
            return answerPageResponseVM;
        });
        return RestResponse.ok(vmPageInfo);
    }

    @PostMapping("/edit")
    public RestResponse edit(@RequestBody @Valid ExamPaperSubmitVM examPaperSubmitVM){
        boolean notJudge = examPaperSubmitVM.getAnswerItems().stream().anyMatch(i -> i.getDoRight() == null && i.getScore() == null);
        if (notJudge){
            return RestResponse.fail(2,"有未批改题目");
        }

        ExamPaperAnswer examPaperAnswer = examPaperAnswerService.selectById(examPaperSubmitVM.getId());
        ExamPaperAnswerStatusEnum answerStatusEnum = ExamPaperAnswerStatusEnum.fromCode(examPaperAnswer.getStatus());
        if (answerStatusEnum == ExamPaperAnswerStatusEnum.Complete){
            return RestResponse.fail(3,"试卷已完成");
        }
        String score = examPaperAnswerService.judge(examPaperSubmitVM);
        User user = getCurrentUser();
        UserEventLog userEventLog = new UserEventLog(user.getId(), user.getUserName(), user.getRealName(), new Date());
        String content = user.getUserName() + "批改试卷：" + examPaperAnswer.getPaperName() + "得分：" + score;
        userEventLog.setContent(content);
        eventPublisher.publishEvent(new UserEvent(userEventLog));
        return RestResponse.ok(score);
    }

}
